package com.msh.artascope.web.common.interceptor;

import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor;
import com.msh.frame.client.model.ApplicationServer;
import com.msh.frame.client.util.LocalDevelopmentUtil;
import com.msh.frame.web.util.HttpServletRequestUtil;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;

/**
 * 本地调试开发拦截器
 * 重新构建转发地址，可以将配置信息转发到本地调试
 *
 */
public class LocalDevelopmentInterceptor implements GlobalInterceptor {

  @Override
  public Response intercept(@NotNull Chain chain) throws IOException {
    Request request = chain.request();
    Builder builder = null;

    HttpServletRequest currentRequest = HttpServletRequestUtil.getCurrentRequest();
    String pathRoute = currentRequest.getHeader(LocalDevelopmentUtil.HEADER_PATH_ROUTE);
    String serverRoute = currentRequest.getHeader(LocalDevelopmentUtil.HEADER_SERVER_ROUTE);
    HttpUrl url = request.url();
    String path = url.encodedPath();
    ApplicationServer applicationServer = LocalDevelopmentUtil.getPathRoute(pathRoute, path);
    if(null == applicationServer){
      applicationServer = LocalDevelopmentUtil.getServerRoute(serverRoute, url.host());
    }
    if(StringUtils.hasText(pathRoute) || StringUtils.hasText(serverRoute)){
      builder = request.newBuilder();
      if(StringUtils.hasText(pathRoute)){
        builder.addHeader(LocalDevelopmentUtil.HEADER_PATH_ROUTE, pathRoute);
      }
      if(StringUtils.hasText(serverRoute)){
        builder.addHeader(LocalDevelopmentUtil.HEADER_SERVER_ROUTE, serverRoute);
      }
    }

    if(null == applicationServer){
      if(null == builder){
        return chain.proceed(request);
      }
      return chain.proceed(builder.build());
    }
    if(null == builder){
      builder = request.newBuilder();
    }
    HttpUrl.Builder urlBuilder = url.newBuilder();
    String scheme = applicationServer.getScheme();
    String host = applicationServer.getHost();
    Integer port = applicationServer.getPort();
    String newPath = applicationServer.getPath();
    if(StringUtils.hasText(scheme)){
      urlBuilder.scheme(scheme);
    }
    if(StringUtils.hasText(host)){
      urlBuilder.host(host);
    }
    if(null !=port){
      urlBuilder.port(port);
    }
    if(StringUtils.hasText(newPath)){
      urlBuilder.encodedPath(newPath);
    }
    ;
    return chain.proceed(builder.url(urlBuilder.build()).build());
  }

}
